package com.ziyucoding.springboot.labs.lab3.rocketmqdemo.producer;

import com.ziyucoding.springboot.labs.lab3.rocketmqdemo.message.Demo2Message;
import com.ziyucoding.springboot.labs.lab3.rocketmqdemo.message.Demo3Message;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 示例3的生产者（用于发送延迟消息）
 *
 * @author ziyucoding
 * @date 2022-10-20
 **/
@Component
public class Demo3Producer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 同步发送延迟消息
     *
     * @param id
     * @param delayLevel
     * @return org.apache.rocketmq.client.producer.SendResult
     **/
    public SendResult syncSendDelay(Integer id, int delayLevel) {
        // 创建消息
        Message message = MessageBuilder.withPayload(new Demo3Message(id)).build();
        // 同步发送消息
        SendResult result = rocketMQTemplate.syncSend(Demo3Message.TOPIC, message, 30 * 1000,
                delayLevel);
        return result;
    }

    /**
     * 异步发送延迟消息
     *
     * @param id
     * @param delayLevel
     * @param callback
     * @return void
     **/
    public void aSyncSendDelay(Integer id, int delayLevel, SendCallback callback) {
        // 创建消息
        Message message = MessageBuilder.withPayload(new Demo3Message(id)).build();
        // 异步发送消息
        rocketMQTemplate.asyncSend(Demo3Message.TOPIC, message, callback, 30 * 1000, delayLevel);
    }
}
